<template>
  <div class="auction-detail-container">
    <!-- 商品信息区 -->
    <el-card class="product-card glassmorphism">
      <div class="product-header">
        <div class="image-wrapper">
          <el-image 
          :src="'http://localhost:8092' + productData?.images" 
            fit="cover" 
            class="main-image hover-zoom"
            :preview-src-list="previewImages"
          >
            <template #error>
              <div class="image-fallback">
                <el-icon :size="50"><Picture/></el-icon>
              </div>
            </template>
          </el-image>
        </div>
        <div class="product-info">
          <h1 class="product-title gradient-text">{{ productData.productName }}</h1>
          <div class="meta-info">
            <el-tag type="info" class="custom-tag">{{ productData.grade }}</el-tag>
            <el-tag type="info" class="custom-tag">{{ productData.major }}</el-tag>
          </div>
          <div class="price-section neumorphism">
            <div class="current-price">
              <span class="label">当前最高价</span>
              <span class="value">¥{{ formatPrice(auctionData.currentPrice) }}</span>
            </div>
            <div class="start-price">
              <el-icon><PriceTag /></el-icon>
              起拍价 ¥{{ formatPrice(auctionData.startPrice) }}
            </div>
          </div>
          <div class="time-remaining">
    <transition name="fade" mode="out-in">
      <div v-if="auctionStatus === 0" key="countdown" class="countdown-card">
        <div class="time-text">
          <el-icon><Clock /></el-icon>
          开始倒计时：{{ formatRemainTime(countdown.start) }}
        </div>
      </div>

      <div v-else-if="auctionStatus === 1" key="remaining" class="countdown-card pulse">
        <div class="time-text ending">
          <el-icon><AlarmClock /></el-icon>
          剩余时间：{{ formatRemainTime(countdown.end) }}
        </div>
      </div>

      <div v-else key="ended" class="ended-card">
        <el-icon class="ended-icon"><CircleCloseFilled /></el-icon>
        <span class="ended-text">竞拍已结束</span>
      </div>
    </transition>
  </div>
        </div>
      </div>
      
      <!-- 商品描述 -->
      <div class="product-description">
        <h3 class="section-title"><el-icon><Document /></el-icon> 商品详情</h3>
        <p class="description-text">{{ productData.introduction }}</p>
      </div>
    </el-card>

    <!-- 出价区 -->
    <el-card class="bid-section glassmorphism">
      <div class="bid-form">
        <h3 class="section-title"><el-icon><EditPen /></el-icon> 出价竞拍</h3>
        <el-form :model="bidForm" :rules="bidRules" ref="bidFormRef">
          <el-form-item label="出价金额" prop="amount">
            <el-input-number 
              v-model="bidForm.amount"
              :min="minBidAmount"
              :step="50"
              controls-position="right"
              class="bid-input"
              placeholder="请输入出价金额"
            >
              <template #prefix>
                <el-icon><Coin /></el-icon>
              </template>
            </el-input-number>
          </el-form-item>
          <el-button 
            type="primary" 
            @click="submitBid"
            :disabled="auctionStatus !== 1"
            class="bid-button"
          >
            <el-icon><Aim /></el-icon>
            立即出价
          </el-button>
        </el-form>
      </div>

      <!-- 出价记录 -->
      <div class="bid-history">
        <h3 class="section-title"><el-icon><Clock /></el-icon> 出价记录</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(bid, index) in bidHistory"
            :key="index"
            :timestamp="formatTime(bid.bidTime)"
            class="timeline-item"
          >
            <div class="bid-record">
              <el-avatar :size="32" class="user-avatar">{{ bid.userId.toString().slice(-2) }}</el-avatar>
              <el-tag 
                :type="bid.isWinning ? 'success' : 'info'" 
                class="bid-tag"
                effect="dark"
              >
                <span class="bid-price">¥{{ bid.bidPrice }}</span>
                <span class="bid-time">{{ formatTime(bid.bidTime) }}</span>
              </el-tag>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'
import {
  Clock,
  AlarmClock,
  CircleCloseFilled,
  Picture,
  PriceTag,
  Document,
  EditPen,
  Coin,
  Aim
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const productId = ref(route.query.productId)

// 数据获取
const productData = ref({})
const auctionData = ref({
  startTime: 0,
  endTime: 0,
})
const bidHistory = ref([])

const fetchData = async () => {
  try {
    const productRes = await axios.get('http://localhost:8092/product/getDetailBySingleId', {
      params: { productId: productId.value }
    })
    productData.value = productRes.data.data[0]
    
    const auctionRes = await axios.get('http://localhost:8092/auction/getByProductId', {
      params: { productId: productId.value }
    })
    auctionData.value = {
      ...auctionRes.data.data,
      startTime: new Date(auctionRes.data.data.startTime).getTime(),
      endTime: new Date(auctionRes.data.data.endTime).getTime()
    }
    
    const bidRes = await axios.get('http://localhost:8092/bid/history', {
      params: { auctionId: auctionData.value.auctionId }
    })
    bidHistory.value = bidRes.data.data
    
  } catch (error) {
    console.error('数据获取失败:', error)
  }
}

// 倒计时逻辑
const currentTime = ref(Date.now())
let timer = null

const countdown = computed(() => ({
  start: auctionData.value.startTime - currentTime.value,
  end: auctionData.value.endTime - currentTime.value
}))

// 状态判断逻辑与列表页保持一致
const auctionStatus = computed(() => {
  if (!auctionData.value.startTime || !auctionData.value.endTime) return -1
  
  const now = currentTime.value
  if (now < auctionData.value.startTime) return 0
  if (now > auctionData.value.endTime) return 2
  return 1
})
// 时间格式化
const formatRemainTime = (milliseconds) => {
  if (milliseconds <= 0) return '00:00:00'
  
  const hours = Math.floor(milliseconds / (1000 * 60 * 60))
  const minutes = Math.floor((milliseconds % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((milliseconds % (1000 * 60)) / 1000)
  
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}
// 表单逻辑
const bidForm = ref({ amount: 0 })
const bidFormRef = ref(null)
const minBidAmount = computed(() => Number(auctionData.value.currentPrice) + 50)

const bidRules = {
  amount: [
    { required: true, message: '请输入出价金额', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value < minBidAmount.value) {
        callback(new Error(`出价必须高于当前价格 ${minBidAmount.value}`))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ]
}

const submitBid = async () => {
  try {
    await bidFormRef.value.validate()
    const res = await axios.post('http://localhost:8092/bid/create', {
      auctionId: auctionData.value.auctionId,
      bidPrice: bidForm.value.amount,
      productId:auctionData.value.productId
    }, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    })
    
    if(res.data.code === 200) {
      ElMessage.success('出价成功')
      fetchData()
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '出价失败')
  }
}

// 工具函数
const formatPrice = (price) => Number(price).toFixed(2)
const formatTime = (datetime) => new Date(datetime).toLocaleString()

// 生命周期
onMounted(() => {
  fetchData()
  // 使用箭头函数保持this指向
  timer = setInterval(() => {
    currentTime.value = Date.now()
  }, 1000)
})

onBeforeUnmount(() => clearInterval(timer))
</script>

<style scoped>
.auction-detail-container {
  max-width: 1400px;
  margin: 2rem auto;
  padding: 2rem;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
}

.glassmorphism {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.18);
}

.product-card {
  margin-bottom: 2rem;
  border: none;
}

.product-header {
  display: flex;
  gap: 3rem;
  padding: 2rem;
}

.image-wrapper {
  flex: 0 0 500px;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.main-image {
  width: 100%;
  height: 400px;
  transition: transform 0.3s ease;
}

.hover-zoom:hover {
  transform: scale(1.03);
}

.product-info {
  flex: 1;
}

.gradient-text {
  background: linear-gradient(45deg, #2c3e50, #3498db);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 2.5rem;
  margin-bottom: 1.5rem;
}

.custom-tag {
  border-radius: 8px;
  padding: 8px 15px;
  margin-right: 10px;
  background: rgba(52, 152, 219, 0.1);
  border-color: rgba(52, 152, 219, 0.2);
  color: #2c3e50;
}

.neumorphism {
  padding: 1.5rem;
  border-radius: 15px;
  background: #ffffff;
  box-shadow: 8px 8px 16px #f0f0f0,
             -8px -8px 16px #ffffff;
}

.price-section {
  margin: 2rem 0;
}

.current-price {
  display: flex;
  align-items: baseline;
  gap: 1rem;
  margin-bottom: 1rem;
}

.label {
  font-size: 16px;
  color: #7f8c8d;
}

.value {
  font-size: 2.2rem;
  color: #e67e22;
  font-weight: 700;
}

.start-price {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #95a5a6;
  font-size: 14px;
}

.time-remaining {
  margin: 2rem 0;
}

.countdown-card {
  padding: 1.5rem;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  border: 1px solid rgba(234, 234, 234, 0.5);
}

.time-display {
  font-family: 'Courier New', monospace;
  font-size: 1.8rem;
  color: #2ecc71;
}

.ending {
  color: #e74c3c;
}

.ended-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 1.5rem;
  background: rgba(231, 76, 60, 0.1);
  border-radius: 12px;
}

.ended-icon {
  color: #e74c3c;
  font-size: 24px;
}

.ended-text {
  color: #e74c3c;
  font-weight: 500;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #2c3e50;
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
}

.description-text {
  line-height: 1.8;
  color: #7f8c8d;
  font-size: 15px;
}

.bid-section {
  padding: 2rem;
}

.bid-input {
  width: 250px;
}

.bid-button {
  padding: 12px 30px;
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.3s;
  background: linear-gradient(45deg, #3498db, #2980b9);
}

.bid-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
}

.timeline-item {
  padding: 10px 0;
}

.bid-record {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-avatar {
  background: linear-gradient(45deg, #3498db, #2980b9);
  color: white;
}

.bid-tag {
  padding: 12px 20px;
  border-radius: 8px;
  border: none;
}

.bid-price {
  font-weight: 700;
  margin-right: 15px;
}

.bid-time {
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.9em;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.pulse {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.02); }
  100% { transform: scale(1); }
}

@media (max-width: 1200px) {
  .product-header {
    flex-direction: column;
  }
  
  .image-wrapper {
    flex: none;
    width: 100%;
  }
  
  .main-image {
    height: 300px;
  }
}
.time-text {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  padding: 8px;
  background: #f8fafc;
  border-radius: 8px;
  
  &.ending {
    color: #e53e3e;
    font-weight: 600;
  }
  
  .el-icon {
    font-size: 16px;
  }
}

.countdown-card {
  padding: 12px;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.ended-card {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #718096;
  padding: 12px;
}
</style>